<template>
    <!-- 按钮栏 -->
    <div class="flex flex-wrap ml-4 mb-4 gap-2">
        <!-- 搜索框 -->
        <el-input
            v-model="searchDictionaryValue"
            style="width: 180px"
            placeholder="请输入字典的关键字"
            clearable
            @clear="inputClearEvent"
            @keydown.enter="searchDictionaryEvent"
        />
        <el-button :icon="Search" type="primary" @click="searchDictionaryEvent">搜索</el-button>
        <!-- 选项组 -->
        <el-button-group>
            <!-- 刷新 -->
            <el-button type="primary" :icon="Refresh" @click="updateForm()">刷新</el-button>
            <!-- 添加 -->
            <el-button type="primary" :icon="Plus" @click="addDictionaryEvent">添加</el-button>
            <!-- 一键添加权限 -->
            <el-button type="primary" :icon="MagicStick" @click="updateAllDictionaryRolesEvent">一键添加权限</el-button>
            <!-- 删除 -->
            <el-popconfirm title="删除后将无法找回，谨慎操作！" @confirm="deleteDictionaryEvent">
                <template #reference>
                    <el-button type="primary" :icon="Delete">删除</el-button>
                </template>
            </el-popconfirm>
        </el-button-group>
        <!-- 导入 -->
        <el-upload
            ref="upload"
            :auto-upload="false"
            :show-file-list="false"
            @change="handleFileChange"
            :limit="1"
            :on-exceed="handleExceed"
            accept=".json"
        >
            <el-button type="primary" :icon="TableImport">.json格式导入</el-button>
        </el-upload>
        <!-- 导出 -->
        <el-button type="primary" :icon="TableExport" @click="exportDictionaryEvent">.json格式导出</el-button>
    </div>
    <!-- 表格 -->
    <div style="height: calc(100vh - 130px); width: 100%">
        <el-auto-resizer>
            <template #default="{ height, width }">
                <el-table-v2 :columns="columns" :data="data" :width="width" :height="height" :row-height="120" fixed />
            </template>
        </el-auto-resizer>
    </div>

    <!-- 添加字典表单Dialog -->
    <el-dialog v-model="addDictionaryVisible" title="添加字典" width="50%" draggable>
        <el-form ref="dictionaryFormRef" :rules="rules" :model="addDictionaryForm" label-width="80px">
            <el-form-item label="字典字段" required prop="word">
                <el-input v-model="addDictionaryForm.word" />
            </el-form-item>
            <el-form-item label="字典解释" required prop="definition">
                <el-input v-model="addDictionaryForm.definition" />
            </el-form-item>
            <el-form-item label="表格宽度" required prop="width">
                <el-input v-model="addDictionaryForm.width" />
            </el-form-item>
            <el-form-item label="字典类型" required prop="width">
                <el-select v-model="addDictionaryForm.type" placeholder="请选择类型">
                    <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" :disabled="item.disabled" />
                </el-select>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button type="primary" @click="addDictionarySubmitEvent"> 提交 </el-button>
            </div>
        </template>
    </el-dialog>

    <!-- 修改字典角色权限Dialog -->
    <el-dialog v-model="updateDictionaryRolesVisible" width="60%" draggable :close-on-click-modal="false">
        <template #header>
            <el-text v-for="(item, index) in updateDictionaryRolesTitle" :key="index" :type="item.type">
                {{ item.text }}
            </el-text>
        </template>
        <div class="w-full flex flex-wrap justify-center mb-4 mt-4">
            <el-transfer
                class="w-full flex justify-center items-center"
                v-model="selectedRoles"
                :data="rolesData"
                :titles="['角色列表', '已选角色']"
                filterable
                :filter-method="filterRolesMethod"
                filter-placeholder="搜索关键字"
                @change="rolesChangeEvent"
            />
            <el-button @click="updateDictionaryRolesSubmitEvent">提交</el-button>
        </div>
    </el-dialog>
</template>

<script setup lang="tsx">
import { getDictionaryList, getAllRole, importDictionary, addDictionary } from '@/api/system';
import { updateDictionary, updateDictionaryRoles, updateAllDictionaryRoles, deleteDictionary } from '@/api/system';
import queryDictionaryList from '@/store/dictionary';
import { Refresh, Plus, Delete, Search, MagicStick } from '@element-plus/icons-vue';
import { ElCheckbox, type UploadFile, type UploadFiles, type UploadInstance, type UploadProps, type UploadRawFile } from 'element-plus';
import { type FormInstance, type CheckboxValueType, type Column, type FormRules } from 'element-plus';
import { type TransferKey, type TransferDirection } from 'element-plus';
import { ElInput, ElSelect, ElOption, ElButton, genFileId, ElTag } from 'element-plus';
import { TableImport, TableExport } from '@vicons/tabler';
import { FunctionalComponent } from 'vue';
import dayjs from 'dayjs';
import { useUserStore } from '@/store/modules/user';

onMounted(() => {
    updateForm();
});

/* ******************************通用属性/方法****************************** */
const useUser = useUserStore();
// 表格数据
const data = reactive<AjaxResponse['dictionaryList']>([]);
// 表格数据缓存
let dataCache: AjaxResponse['dictionaryList'] = [];
// 被选择的表格数据id
const selected = reactive<string[]>([]);

// 更新表格的方法
const updateForm = (message: string = '查询字典成功') => {
    // 清空表格数据
    data.length = 0;
    selected.splice(0);
    // 获取字典列表
    getDictionaryList().then((res) => {
        if (!(res.data && res.data.length)) {
            ElMessage.info('没有可用的字典列表');
            return;
        }
        ElMessage({
            message,
            type: 'success',
            grouping: true,
        });
        // 加工成表单响应式数据
        res.data.forEach((item, index) => {
            item.order = index + 1;
            item.checked = false;
            item.editing = false;
            data.push({ ...item });
        });
        // 缓存数据
        dataCache = res.data;
        // 同步至sessionStorage
        queryDictionaryList(res.data);
    });
};
// 更新数据的方法
const updateData = (id: string, word: string, definition: string, width: number, type: any) => {
    updateDictionary({ _id: id, word: word, definition: definition, width: width, type: type }).then(() => {
        updateForm('更新成功');
    });
};

/* ******************************原生el-table-v2 表格属性****************************** */
// checkbox函数式组件
type CheckBoxCellProps = {
    value: boolean;
    intermediate?: boolean;
    onChange: (value: CheckboxValueType) => void;
};
const CheckBoxCell: FunctionalComponent<CheckBoxCellProps> = ({ value, intermediate = false, onChange }) => {
    return <ElCheckbox size={'large'} modelValue={value} indeterminate={intermediate} onChange={onChange} />;
};

// input函数式组件
type InputCellProps = {
    value: string;
    onInput: (value: string) => void;
    onBlur: () => void;
};
const InputCell: FunctionalComponent<InputCellProps> = ({ value, onBlur, onInput }) => {
    return <ElInput onInput={onInput} onBlur={onBlur} modelValue={value} />;
};

// select函数式组件
type SelectCellProps = {
    value: string;
    onChange: (value: string) => void;
};
const SelectCell: FunctionalComponent<SelectCellProps> = ({ value, onChange }) => {
    return (
        <ElSelect v-model={value} onChange={onChange}>
            {options.map((item) => {
                return <ElOption value={item.value} label={item.label} disabled={item.disabled} />;
            })}
        </ElSelect>
    );
};

// input原始值
let inputOriginValue = '';
// 表格列配置
const columns: Column<any>[] = [
    {
        key: 'checked',
        width: 50,
        title: '选择',
        align: 'center',
        cellRenderer: ({ rowData }) => {
            const onChange = (value: CheckboxValueType) => {
                if (value) {
                    // 添加被选数据
                    selected.push(rowData._id);
                    // 删除重复数据
                    function deleteArrayRepeat() {
                        // 缓存
                        let newArr: any[] = [];
                        for (let index = 0; index < selected.length; index++) {
                            if (newArr.indexOf(selected[index]) == -1) {
                                // 缓存中不存在则添加该索引
                                newArr.push(selected[index]);
                            } else {
                                // 缓存中存在则删除该索引
                                selected.splice(index, 1);
                            }
                        }
                    }
                    deleteArrayRepeat();
                } else {
                    // 删除被选数据
                    const index = selected.indexOf(rowData._id);
                    index !== -1 ? selected.splice(index, 1) : '';
                }
                rowData.checked = value;
            };
            return <CheckBoxCell value={rowData.checked} onChange={onChange} />;
        },
        headerCellRenderer: () => {
            const onChange = (value: CheckboxValueType) => {
                // 全选操作
                selected.length = 0;
                if (!value) {
                    // 全不选
                    data.forEach((item) => (item.checked = value as boolean));
                } else {
                    // 全选
                    data.forEach((item) => {
                        selected.push(item._id);
                        item.checked = value as boolean;
                    });
                }
            };
            const allSelected = data.every((row: any) => row.checked); // 初始全选检测
            const containsChecked = data.some((row: any) => row.checked); // 初始中间态检测

            return <CheckBoxCell value={allSelected} intermediate={containsChecked && !allSelected} onChange={onChange} />;
        },
    },
    { key: 'order', dataKey: 'order', width: 60, title: '编号', align: 'center' },
    {
        key: 'createdAt',
        dataKey: 'createdAt',
        width: 170,
        title: '创建时间',
        align: 'center',
        cellRenderer: ({ rowData }) => {
            const Shanghai = dayjs(rowData.createdAt).format('YYYY-MM-DD HH:mm:ss');
            return <div>{Shanghai}</div>;
        },
    },
    {
        key: 'word',
        dataKey: 'word',
        width: 280,
        title: '字段',
        align: 'center',
        cellRenderer: ({ rowData, column }) => {
            // 检测输入框数据变动
            const onInput = (value: string) => {
                rowData[column.dataKey!] = value;
                inputOriginValue = rowData[column.dataKey!];
            };

            // 输入框编辑模式
            const onEnterEditMode = () => {
                rowData.editing = true;
            };
            // 输入框退出编辑模式 -- 更新到服务器
            const onExitEditMode = () => {
                // 退出编辑模式
                rowData.editing = false;
                // 对比新旧值
                if (rowData[column.dataKey!] !== inputOriginValue) {
                    updateData(rowData._id, rowData.word, rowData.definition, rowData.width, rowData.type);
                }
            };

            return rowData.editing ? (
                <InputCell value={rowData[column.dataKey!]} onInput={onInput} onBlur={onExitEditMode} />
            ) : (
                <div class="table-v2-inline-editing-trigger" onClick={onEnterEditMode}>
                    {rowData[column.dataKey!]}
                </div>
            );
        },
    },
    {
        key: 'definition',
        dataKey: 'definition',
        width: 180,
        title: '释义',
        align: 'center',
        cellRenderer: ({ rowData, column }) => {
            // 检测输入框数据变动
            const onInput = (value: string) => {
                rowData[column.dataKey!] = value;
            };

            // 输入框编辑模式
            const onEnterEditMode = () => {
                rowData.editing = true;
            };
            // 输入框退出编辑模式 -- 更新到服务器
            const onExitEditMode = () => {
                rowData.editing = false;
                // 对比新旧值
                if (rowData[column.dataKey!] !== inputOriginValue) {
                    updateData(rowData._id, rowData.word, rowData.definition, rowData.width, rowData.type);
                }
            };

            return rowData.editing ? (
                <InputCell value={rowData[column.dataKey!]} onInput={onInput} onBlur={onExitEditMode} />
            ) : (
                <div class="table-v2-inline-editing-trigger" onClick={onEnterEditMode}>
                    {rowData[column.dataKey!]}
                </div>
            );
        },
    },
    {
        key: 'width',
        dataKey: 'width',
        width: 100,
        title: '表格宽度',
        align: 'center',
        cellRenderer: ({ rowData, column }) => {
            // 检测输入框数据变动
            const onInput = (value: string) => {
                rowData[column.dataKey!] = value;
            };

            // 输入框编辑模式
            const onEnterEditMode = () => {
                rowData.editing = true;
            };
            // 输入框退出编辑模式 -- 更新到服务器
            const onExitEditMode = () => {
                rowData.editing = false;
                // 对比新旧值
                if (rowData[column.dataKey!] !== inputOriginValue) {
                    updateData(rowData._id, rowData.word, rowData.definition, rowData.width, rowData.type);
                }
            };

            return rowData.editing ? (
                <InputCell value={rowData[column.dataKey!]} onInput={onInput} onBlur={onExitEditMode} />
            ) : (
                <div class="table-v2-inline-editing-trigger" onClick={onEnterEditMode}>
                    {rowData[column.dataKey!]}
                </div>
            );
        },
    },
    {
        key: 'type',
        dataKey: 'type',
        width: 180,
        title: '表格类型',
        align: 'center',
        cellRenderer: ({ rowData, column }) => {
            // 检测输入框数据变动
            const onChange = (value: string) => {
                rowData[column.dataKey!] = value;
                updateDictionary({
                    _id: rowData._id,
                    word: rowData.word,
                    definition: rowData.definition,
                    width: rowData.width,
                    type: rowData.type,
                }).then(() => {
                    updateForm('更新成功');
                });
            };

            return <SelectCell value={rowData[column.dataKey!]} onChange={onChange} />;
        },
    },
    {
        key: 'roles',
        dataKey: 'roles',
        width: 360,
        title: '查看角色组',
        align: 'center',
        cellRenderer: ({ rowData }) => {
            // 显示角色列表dialog
            const onClick = () => {
                updateRolesEvent(rowData._id, rowData.roles);
            };

            return (
                <div class={'w-full flex flex-wrap gap-2 justify-center'}>
                    <div class={'w-full flex flex-wrap gap-2 justify-center'}>
                        {rowData.roles.map((item: string) => (
                            <ElTag size={'small'}>{item}</ElTag>
                        ))}
                    </div>
                    <ElButton size={'small'} text type={'warning'} onClick={onClick}>
                        编辑
                    </ElButton>
                </div>
            );
        },
    },
    {
        key: 'updatedAt',
        dataKey: 'updatedAt',
        width: 170,
        title: '更新时间',
        align: 'center',
        cellRenderer: ({ rowData }) => {
            const Shanghai = dayjs(rowData.updatedAt).format('YYYY-MM-DD HH:mm:ss');
            return <div>{Shanghai}</div>;
        },
    },
    { key: 'creator', dataKey: 'creator', width: 100, title: '创建者', align: 'center' },
];

/* ******************************搜索字典属性/方法****************************** */
// 搜索值
const searchDictionaryValue = ref('');
// 搜索事件
const searchDictionaryEvent = () => {
    if (searchDictionaryValue.value == '') {
        // 原始数据
        data.length = 0;
        dataCache.forEach((item) => {
            data.push(item);
        });
    } else {
        // 筛选数据
        data.length = 0;
        dataCache.forEach((item) => {
            if (item.word.includes(searchDictionaryValue.value) || item.definition.includes(searchDictionaryValue.value)) {
                data.push(item);
            }
        });
    }
};
// 输入框清空事件
const inputClearEvent = () => {
    // 原始数据
    data.length = 0;
    dataCache.forEach((item) => {
        data.push(item);
    });
};

/* ******************************导入字典属性/方法****************************** */
// 上传实例
const upload = ref<UploadInstance>();
// 上传文件
const handleFileChange = (uploadFile: UploadFile, _uploadFiles: UploadFiles) => {
    // 读取文件
    const reader = new FileReader();
    // @ts-ignore
    reader.readAsText(uploadFile.raw);
    // 当读取完成时
    reader.onload = () => {
        // @ts-ignore
        const data = JSON.parse(reader.result);
        // 检查数据的合法性并加工数据
        if (checkData(data)) {
            importDictionaryEvent(data);
        }
    };
};
// 上传文件超出限制覆盖前一个文件
const handleExceed: UploadProps['onExceed'] = (files) => {
    upload.value!.clearFiles();
    const file = files[0] as UploadRawFile;
    file.uid = genFileId();
    upload.value!.handleStart(file);
};
// 检查数据的合法性
const checkData = (data: any): Boolean => {
    // 检测数据类型
    if (typeof data !== 'object') {
        ElMessage.error('导入的数据无法识别');
        return false;
    }

    // 检测数据长度
    if (data.length === 0) {
        ElMessage.error('数据为空无法导入');
        return false;
    }

    // 检测每个数据
    for (let index = 0; index < data.length; index++) {
        const element = data[index];
        let count = 0;
        // 检测每个数据字段
        for (const key in element) {
            if (Object.prototype.hasOwnProperty.call(element, key)) {
                if (key == 'word' || key == 'definition' || key == 'width' || key == 'type') {
                    count++;
                } else {
                    ElMessage.error('数据格式不正确');
                    return false;
                }
            }
        }
        // 检测数据字段数量
        if (count !== 4) {
            ElMessage.error('数据格式不正确');
            return false;
        }
    }

    return true;
};
// 导入字典事件
const importDictionaryEvent = (data) => {
    const _data = data.map((item) => {
        return {
            word: item.word,
            definition: item.definition,
            width: item.width,
            type: item.type,
            creator: useUserStore().username,
            creatorId: useUserStore().id,
        };
    });
    importDictionary(_data).then(() => {
        updateForm('导入成功');
    });
};

/* ******************************添加字典属性/方法****************************** */
// 添加字典的visible
const addDictionaryVisible = ref(false);
// 添加字典的表单实例
const dictionaryFormRef = ref<FormInstance>();
// 添加字典的dialog事件
const addDictionaryEvent = () => (addDictionaryVisible.value = true);
// 表单选项
const options: { disabled: boolean; value: string; label: string }[] = [
    { disabled: false, value: 'text', label: '文本' },
    { disabled: false, value: 'noshow', label: '不显示' },
    { disabled: false, value: 'input', label: '输入框' },
    { disabled: false, value: 'textarea', label: '文本域' },
    { disabled: false, value: 'select', label: '选择器' },
    { disabled: false, value: 'checkbox', label: '多选框' },
    { disabled: false, value: 'switch', label: '开关' },
    { disabled: false, value: 'date', label: '日期选择器' },
    { disabled: false, value: 'datetime', label: '日期时间选择器' },
    { disabled: false, value: 'upload', label: '上传' },
    { disabled: false, value: 'button', label: '按钮' },
    { disabled: false, value: 'image', label: '图片' },
    { disabled: true, value: 'video', label: '视频' },
    { disabled: true, value: 'audio', label: '音频' },
    { disabled: false, value: 'file', label: '文件' },
];
// 添加字典的表单数据
const addDictionaryForm = reactive<AjaxRequest['dictionary']>({
    word: '',
    definition: '',
    width: 120,
    type: 'text',
});
// 字段验证
const validatorWord = (_rule: any, value: any, callback: any) => {
    if (value === '') {
        callback(new Error('字段不能为空'));
    } else if (!/^[A-Za-z0-9_]{2,30}$/.test(value)) {
        callback(new Error('字段应为2-30位字母'));
    } else {
        callback();
    }
};
// 释义验证
const validatorDefinition = (_rule: any, value: any, callback: any) => {
    if (value === '') {
        callback(new Error('释义不能为空'));
    } else if (!/^[\u4E00-\u9FA5A-Za-z0-9]{2,10}$/.test(value)) {
        callback(new Error('释义应为1-10位中文、英文、数字'));
    } else {
        callback();
    }
};
// 宽度验证
const validatorWidth = (_rule: any, value: any, callback: any) => {
    if (value === '') {
        callback(new Error('宽度不能为空'));
    } else if (!/^[1-9][0-9]{0,2}$/.test(value)) {
        callback(new Error('宽度应为1-999之间的整数'));
    } else {
        callback();
    }
};
// 类型验证
const validatorType = (_rule: any, value: any, callback: any) => {
    if (value === '') {
        callback(new Error('类型不能为空'));
    } else {
        callback();
    }
};
// 添加字典的表单的校验规则
const rules = reactive<FormRules<typeof addDictionaryForm>>({
    word: [
        { validator: validatorWord, trigger: 'change' },
        { validator: validatorWord, trigger: 'blur' },
    ],
    definition: [
        { validator: validatorDefinition, trigger: 'change' },
        { validator: validatorDefinition, trigger: 'blur' },
    ],
    width: [
        { validator: validatorWidth, trigger: 'change' },
        { validator: validatorWidth, trigger: 'blur' },
    ],
    type: [
        { validator: validatorType, trigger: 'change' },
        { validator: validatorType, trigger: 'blur' },
    ],
});
// 添加字典的表单提交事件
const addDictionarySubmitEvent = async () => {
    if (!dictionaryFormRef) return;
    // 表单校验
    dictionaryFormRef.value?.validate((valid) => {
        if (valid) {
            addDictionary({ ...addDictionaryForm, creator: useUser.username, creatorId: useUser.id }).then(() => {
                addDictionaryVisible.value = false;
                updateForm('添加成功');
            });
        } else {
            console.warn('验证表单错误！');
        }
    });
};

/* ******************************修改字典角色权限属性/方法****************************** */
// 修改字典角色权限dialog标题
const updateDictionaryRolesTitle = computed<{ type: any; text: string }[]>(() => {
    if (updateAllsymbol.value && selected.length == 0) {
        // 修改全部字典角色权限
        return [
            {
                type: 'primary',
                text: '修改字典角色权限',
            },
            {
                type: 'warning',
                text: ' -- 当前未勾选字典，本次操作将覆盖所有字典',
            },
            {
                type: 'danger',
                text: ' -- 如果您不想全部覆盖，请尝试勾选需要变更的字典后重试',
            },
        ];
    } else if (updateAllsymbol.value && selected.length !== 0) {
        // 修改全部勾选的字典角色权限
        return [
            {
                type: 'primary',
                text: '修改字典角色权限',
            },
            {
                type: 'warning',
                text: ' -- 本次操作将覆盖所有被勾选的字典',
            },
        ];
    } else {
        // 修改单个字典的角色权限
        return [
            {
                type: 'primary',
                text: '修改字典角色权限',
            },
            {
                type: 'warning',
                text: ' -- 变更单个字典角色权限',
            },
        ];
    }
});
// 角色权限
const rolesData = ref<{ key: number; label: string; disabled: boolean; [key: string]: any }[]>([]);
// 被选择的角色权限
const selectedRoles = ref<number[]>([]);
// 修改字典角色权限的visible
const updateDictionaryRolesVisible = ref(false);
// 修改全部字典角色权限的标识
const updateAllsymbol = ref(false);
// 需要被上传修改字典的角色权限数据
const dictionaryRolesData = reactive<{ dictionaryId: string; roles: string[] }>({ dictionaryId: '', roles: [] });
// 修改 *单个* 字典角色权限的事件 -- 完善上传的id数据/拉取全部角色/已有的角色权限
const updateRolesEvent = (id: string, roles: string[]) => {
    // 清空数据
    rolesData.value.splice(0);
    selectedRoles.value.splice(0);

    // 打开单个更新的标识
    updateAllsymbol.value = false;

    // 完善上传的id数据
    dictionaryRolesData.dictionaryId = id;

    // 获取所有角色
    getAllRole().then((res) => {
        for (let index = 0; index < res.data.length; index++) {
            const role = res.data[index];
            rolesData.value.push({
                key: index + 1,
                label: role.description,
                disabled: false,
            });
        }

        // 填充已有角色
        for (let index = 0; index < roles.length; index++) {
            const role = roles[index];
            const i = rolesData.value.findIndex((item) => item.label === role);
            i !== -1 ? selectedRoles.value.push(i + 1) : '';
        }

        // 打开dialog
        updateDictionaryRolesVisible.value = true;
    });
};
// 修改 *单个* 字典角色权限变更事件 -- 完善上传的角色数据
const rolesChangeEvent = (value: TransferKey[], _direction: TransferDirection, _movedKeys: TransferKey[]) => {
    // 清空数据
    dictionaryRolesData.roles.length = 0;
    // 填充数据
    for (let index = 0; index < value.length; index++) {
        const i = value[index] as number;
        dictionaryRolesData.roles.push(rolesData.value[i - 1].label);
    }
};
// 修改 *全部* 字典角色权限的时间
const updateAllDictionaryRolesEvent = () => {
    // 清空数据
    rolesData.value.splice(0);
    selectedRoles.value.splice(0);

    // 打开全部更新的标识
    updateAllsymbol.value = true;

    // 获取所有角色
    getAllRole().then((res) => {
        for (let index = 0; index < res.data.length; index++) {
            const role = res.data[index];
            rolesData.value.push({
                key: index + 1,
                label: role.description,
                disabled: false,
            });
        }

        // 打开dialog
        updateDictionaryRolesVisible.value = true;
    });
};
// 过滤权限方法
const filterRolesMethod = (query: string, item: any) => {
    return item.label.includes(query);
};
// 提交修改字典角色权限的事件 -- 单个修改 / 全部（勾选）修改
const updateDictionaryRolesSubmitEvent = async () => {
    if (updateAllsymbol.value) {
        // 全部提交修改
        const data: string[] = [];
        for (let index = 0; index < selectedRoles.value.length; index++) {
            const role = selectedRoles.value[index];
            data.push(rolesData.value[role - 1].label);
        }
        updateAllDictionaryRoles(selected, data).then((res) => {
            // 重新拉取数据
            updateForm(res.message);
            // 关闭dialog
            updateDictionaryRolesVisible.value = false;
        });
    } else {
        // 单个提交修改
        updateDictionaryRoles(dictionaryRolesData).then((res) => {
            // 重新拉取数据
            updateForm(res.message);
            // 关闭dialog
            updateDictionaryRolesVisible.value = false;
        });
    }
};

/* ******************************删除字典属性/方法****************************** */
// 删除字典事件
const deleteDictionaryEvent = () => {
    if (selected.length == 0) {
        ElMessage({
            message: '请先勾选要删除的数据！',
            type: 'warning',
            grouping: true,
        });
    } else {
        deleteDictionary(selected).then(() => {
            updateForm('删除成功');
        });
    }
};

/* ******************************导出字典属性/方法****************************** */
// 导出字典事件
const exportDictionaryEvent = () => {
    // 加工导出的数据
    const _data = data.map((item) => {
        return {
            word: item.word,
            definition: item.definition,
            width: item.width,
            type: item.type,
        };
    });
    // 创建一个a标签
    let a: HTMLAnchorElement | null = document.createElement('a');
    // json化导出数据并把地址挂载到a标签上
    a.href = URL.createObjectURL(new Blob([JSON.stringify(_data)]));
    // 设置下载文件名
    a.download = dayjs().format('YYYY-MM-DD_HH-mm-ss@') + 'dictionary.json';
    // 模拟下载
    a.click();
    // 释放内存
    a = null;
};
</script>

<style>
.table-v2-inline-editing-trigger {
    border: 1px transparent dotted;
    padding: 4px;
}

.table-v2-inline-editing-trigger:hover {
    border-color: var(--el-color-primary);
}
</style>
